import { 
    createPost, 
    fetchPosts, 
    fetchPostById,
    likePost,
    unlikePost 
  } from '@/api/post'
  import { createComment, fetchComments } from '@/api/comment'
  
  const state = {
    posts: [],
    userPosts: [],
    post: null,
    loading: false,
    error: null,
    page: 1,
    hasMore: true
  }
  
  const getters = {
    getPostById: (state) => (postId) => {
      return state.posts.find(post => post.id === postId) || null
    }
  }
  
  const mutations = {
    SET_POSTS(state, posts) {
      state.posts = posts
    },
    ADD_POSTS(state, posts) {
      state.posts = [...state.posts, ...posts]
    },
    SET_USER_POSTS(state, posts) {
      state.userPosts = posts
    },
    SET_POST(state, post) {
      state.post = post
    },
    ADD_POST(state, post) {
      state.posts.unshift(post)
    },
    UPDATE_POST(state, { postId, data }) {
      const index = state.posts.findIndex(post => post.id === postId)
      if (index !== -1) {
        state.posts[index] = { ...state.posts[index], ...data }
      }
    },
    DELETE_POST(state, postId) {
      state.posts = state.posts.filter(post => post.id !== postId)
    },
    SET_PAGE(state, page) {
      state.page = page
    },
    SET_HAS_MORE(state, hasMore) {
      state.hasMore = hasMore
    },
    SET_LOADING(state, loading) {
      state.loading = loading
    },
    SET_ERROR(state, error) {
      state.error = error
    }
  }
  
  const actions = {
    async fetchPosts({ commit, state }, reset = false) {
      if (state.loading) return
      
      if (reset) {
        commit('SET_PAGE', 1)
        commit('SET_HAS_MORE', true)
      }
      
      commit('SET_LOADING', true)
      commit('SET_ERROR', null)
      
      try {
        const params = { page: state.page, limit: 10 }
        const response = await fetchPosts(params)
        
        if (reset) {
          commit('SET_POSTS', response.posts)
        } else {
          commit('ADD_POSTS', response.posts)
        }
        
        commit('SET_PAGE', state.page + 1)
        commit('SET_HAS_MORE', response.posts.length > 0)
        
        return response.posts
      } catch (error) {
        commit('SET_ERROR', error.message)
        throw error
      } finally {
        commit('SET_LOADING', false)
      }
    },
    
    async fetchMorePosts({ dispatch }) {
      await dispatch('fetchPosts', false)
    },
    
    async fetchUserPosts({ commit }, userId) {
      commit('SET_LOADING', true)
      commit('SET_ERROR', null)
      
      try {
        const params = { userId }
        const response = await fetchPosts(params)
        commit('SET_USER_POSTS', response.posts)
        return response.posts
      } catch (error) {
        commit('SET_ERROR', error.message)
        throw error
      } finally {
        commit('SET_LOADING', false)
      }
    },
    
    async createPost({ commit }, postData) {
      commit('SET_LOADING', true)
      commit('SET_ERROR', null)
      
      try {
        const post = await createPost(postData)
        commit('ADD_POST', post)
        return post
      } catch (error) {
        commit('SET_ERROR', error.message)
        throw error
      } finally {
        commit('SET_LOADING', false)
      }
    },
    
    async toggleLike({ commit, rootState }, postId) {
      const userId = rootState.auth.user.id
      const post = rootState.post.posts.find(p => p.id === postId)
      
      if (!post) return
      
      try {
        if (post.likes.some(like => like.userId === userId)) {
          // 已点赞，取消点赞
          await unlikePost(postId)
          commit('UPDATE_POST', { 
            postId, 
            data: { 
              likes: post.likes.filter(like => like.userId !== userId),
              likesCount: post.likesCount - 1
            } 
          })
        } else {
          // 未点赞，添加点赞
          await likePost(postId)
          commit('UPDATE_POST', { 
            postId, 
            data: { 
              likes: [...post.likes, { userId }],
              likesCount: post.likesCount + 1
            } 
          })
        }
      } catch (error) {
        console.error('Error toggling like:', error)
        throw error
      }
    },
    
    async addComment({ commit, rootState }, { postId, content }) {
      commit('SET_LOADING', true)
      commit('SET_ERROR', null)
      
      try {
        const comment = await createComment(postId, content)
        
        // 更新帖子的评论列表
        commit('UPDATE_POST', { 
          postId, 
          data: { 
            comments: [...(rootState.post.posts.find(p => p.id === postId)?.comments || []), comment],
            commentsCount: (rootState.post.posts.find(p => p.id === postId)?.commentsCount || 0) + 1
          } 
        })
        
        return comment
      } catch (error) {
        commit('SET_ERROR', error.message)
        throw error
      } finally {
        commit('SET_LOADING', false)
      }
    }
  }
  
  export default {
    namespaced: true,
    state,
    getters,
    mutations,
    actions
  }